from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from apps.areas.models import Area
from django.core.cache import cache
# Create your views here.

class AreaView(View):
    def get(self,request):
        provence_list=cache.get('provence_list')
        if provence_list is None:
            provinces=Area.objects.filter(parents__isnull=True)
            provinces_list=[]
            for provence in provinces:
                provinces_list.append({
                    'id':provence.id,
                    'name':provence.name,
                })
            cache.set('provence_list',provence_list,3600)
        return JsonResponse({'code':0,'errmsg':'ok','province_list':provinces_list})

class SubAreaView(View):
    def get(self,request,id):
        citys_list=cache.get('city:%s'%id)
        if citys_list is None:
            citys=Area.objects.filter(parents=id)
            citys_list=[]
            for city in citys:
                citys_list.append({
                    'id':city.id,
                    'name':city.name,
                })
            cache.set('city:%s'%id,citys_list,3600)
        return JsonResponse({'code':0,'errmsg':'ok','sub_data':{'subs':citys_list}})
